#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <errno.h>

#include "wf_socket_util.h"

#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff;
#endif


int errexit(const char* format, ...)
{
    va_list args;
    
    va_start(args, format);
    vfprintf(stderr, format, args);
    va_end(args);
    exit(1);
    
    
}

int connect_socket(const char *host,
        const char * service,
        const char * transport)
{
    struct hostent * phe;
    struct servent * pse;
    struct protoent * ppe;
    struct sockaddr_in sin;
    
    int sock_id = 0;
    int sock_type = 0;
    
    memset(&sin, 0, sizeof(sin));
    
    sin.sin_family = AF_INET;
    
    // get service entry by name
    if((pse = getservbyname(service, transport)) != 0) {
        sin.sin_port = pse->s_port;
    } else if((sin.sin_port = htons((unsigned short)atoi(service))) == 0) {
        errexit("cannot get %s service etnry", service);
    }
    
    if((phe = gethostbyname(host)) != 0) {
        memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);
    } else if((sin.sin_addr.s_addr = inet_addr(host))==INADDR_NONE) {
        errexit("cannot get %s host entry", host);
    }
    
    if((ppe = getprotobyname(transport))== 0) {
        errexit("cannot get %s protocol entry", transport);
    }
    
    if(strcmp(transport, "udp") == 0) {
        sock_type = SOCK_DGRAM;
    } else {
        sock_type = SOCK_STREAM;
    }
    
    sock_id = socket(PF_INET, sock_type, ppe->p_proto);
    if(sock_id < 0) {
        errexit("cannot create socket %s\n", strerror(errno));
    }
    
    if(connect(sock_id, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
        errexit("cannot connect to %s.%s: %s\n", host, service, strerror(errno));    
    }
    
    return sock_id;
    
}
